package com.bifrost.admin.controller;

import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.common.base.ServerResponse;
import com.bifrost.entity.User;
import com.bifrost.model.param.UserParam;
import com.bifrost.model.vo.UserVO;
import com.bifrost.service.AdminUserService;
import com.bifrost.util.BeanValidator;
import com.bifrost.util.SHA256Util;
import com.bifrost.validator.group.UserAdd;
import com.bifrost.validator.group.UserUpdate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Author by yanxiaobo
 * Date on 2018/4/10$.
 */
@RestController
@RequestMapping("/admin/adminuser")
@Api("后台用户相关接口")
public class AdminUserController {
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    private AdminUserService userService;

    /**
     * 新增用户
     * @param userParam 新增的用户的信息
     * @param roleIds 该用户对应的角色（可以为空）
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation("增加用户")
    @ApiImplicitParams({@ApiImplicitParam(name = "user对象"),
                         @ApiImplicitParam(name = "roleIds",value="角色id",dataType = "数组"),
                            @ApiImplicitParam(name = "merchantStoreIds",value="门店id",dataType = "数组")})
    public ServerResponse add(UserParam userParam, Integer[] roleIds , Long[] merchantStoreIds) throws Exception {
        Map<String,String> errors = BeanValidator.validate(userParam, UserAdd.class);
        if(!errors.isEmpty())
            return ServerResponse.createByError(errors.values());
        return adminUserService.add(userParam,roleIds,merchantStoreIds);
    }

    /**
     * 删除用户
     * @param userIds 要删除的用户对应的id（不可以为空）
     * @return
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "userId",value = "用户id",required = true)
    public ServerResponse delete(Integer[] userIds) {
        return adminUserService.batchDelete(userIds);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiOperation("修改用户信息")
    public ServerResponse edit(UserParam userParam, Integer[] roleIds, Long[] merchantStoreIds, @CurrentAdmin Long currentUser) {
        Map<String,String> errors = BeanValidator.validate(userParam, UserUpdate.class);
        if(!errors.isEmpty()) {
            return ServerResponse.createByError(errors.values());
        }
        ServerResponse response = adminUserService.update(userParam,roleIds,merchantStoreIds,userService.findById(currentUser) );
        if(!response.isSuccess()){
            return response;
        }
        return response;
    }

    /**
     * 获取用户列表
     * @param currentPage 当前要显示页面的页码
     * @param pageSize 每页显示多少条数据
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiOperation("获取用户列表")
    public ServerResponse list(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize, String username , String storeCode) {
        return adminUserService.list(currentPage,pageSize,username,storeCode);
    }

    /**
     * 获取用户详情
     * @param userId
     * @return
     */
    @RequestMapping(value = "/detail",method = RequestMethod.GET)
    @ApiOperation("获取用户详情")
    public ServerResponse detail(Integer userId) {
        return adminUserService.getDetail(userId);
    }

    /**
     * 获取用户信息
     * @param currentUser
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @ApiOperation("用于登录时获取用户信息")
    public ServerResponse info(@CurrentAdmin Long currentUser) {
        UserVO userVO = UserVO.adapter(userService.findById(currentUser) );
        return ServerResponse.createBySuccess(userVO);
    }

    /**
     * 修改管理员用户密码接口
     * @return
     */
    @PostMapping(value = "/updatePassword")
    @ApiOperation("用于管理员用户密码修改")
    public ServerResponse updatePassword(String adminName, String oldPassword, String newPassword, @CurrentAdmin Long currentUser) {
        String updateStatus = adminUserService.updatePassword(adminName,oldPassword,newPassword,userService.findById(currentUser) );
        if("ok".equalsIgnoreCase(updateStatus)){
            return ServerResponse.createBySuccess("密码修改成功");
        }else if("saveError".equalsIgnoreCase(updateStatus)){
            return ServerResponse.createByErrorMsg("修改密码失败");
        }else if("oldPasswordError".equalsIgnoreCase(updateStatus)){
            return ServerResponse.createByErrorMsg("原密码错误");
        }else {
            return ServerResponse.createByErrorMsg("密码修改失败");
        }
    }

    /**
     * 重置管理员用户密码接口
     * @return
     */
    @PostMapping(value = "/resetPassword")
    @ApiOperation("用于管理员用户密码重置")
    public ServerResponse updatePassword(Long adminId , String defaultPassword , @CurrentAdmin Long currentUser) {
        String updateStatus = adminUserService.resetPassword(adminId,defaultPassword,userService.findById(currentUser) );
        if("ok".equalsIgnoreCase(updateStatus)){
            return ServerResponse.createBySuccess("密码重置成功");
        }else if("adminIdError".equalsIgnoreCase(updateStatus)){
            return ServerResponse.createByErrorMsg("未找到账户信息");
        }else if("resetError".equalsIgnoreCase(updateStatus)){
            return ServerResponse.createByErrorMsg("密码重置失败");
        }else {
            return ServerResponse.createByErrorMsg("密码重置失败");
        }
    }

    /**
     * 重置管理员用户密码接口
     *
     * @return
     */
    @GetMapping(value = "/formatPassword")
    public ServerResponse updatePassword(@RequestParam String password) {
        return ServerResponse.createBySuccess("data",SHA256Util.SHA256EncodeToBase64(DigestUtils.md5DigestAsHex(password.getBytes())));
    }
}